package cn.com.chengmandian.company.exceptions;

import cn.com.chengmandian.core.common.constants.ResponseCode;
import cn.com.chengmandian.core.web.exceptions.BadResponseException;
import cn.com.chengmandian.core.web.pojo.AjaxResult;
import cn.com.chengmandian.core.web.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseBody
@Slf4j
@ControllerAdvice
public class DefaultExceptionAdvice {
    /**
     * IllegalArgumentException异常处理返回json
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({IllegalArgumentException.class})
    public AjaxResult illegalArgumentException(IllegalArgumentException e) {
        return AjaxResult.error(e.getMessage());
    }

    /**
     * BadResponseException自定义用户端异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({BadResponseException.class})
    public AjaxResult badResponseException(BadResponseException e) {
        return AjaxResult.error(e.getCode(), e.getMessage(), e.getData());
    }

    /**
     * 捕获全部系统异常，返回200状态码。正式环境只返回错误类名
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({Exception.class})
    public AjaxResult exception(Exception e) {
        log.error(e.getMessage(), e);
        if (SpringContextUtil.isDev()) {
            return AjaxResult.error(ResponseCode.ERROR,  e.getClass().getSimpleName() + ":" + e.getMessage());
        } else {
            return AjaxResult.error(ResponseCode.ERROR, "系统异常，请稍后再试：" + e.getClass().getSimpleName());
        }
    }
}
